﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<!-- 12. Write a function that creates a HTML UL using a 
			template for every HTML LI. The source of the list 
			should an array of elements. Replace all 
			placeholders marked with –{…}–  with the value of 
			the corresponding property of the object. Example:
		
		<div data-type="template" id="list-item">
		<strong>-{name}-</strong> <span>-{age}-</span>
		</div> 
		
		var people = [{name: "Peter", age: 14},…];
		var tmpl = document.getElementById("list-item").innerHtml;
		var peopleList = generateList(people,template);
		//peopleList = "<ul><li><strong>Peter</strong> 
		<span>14</span></li><li>…</li>…</ul>" -->
	<style>
		ul {
			list-style-type: none;
		}

			strong, span {
				border-bottom: 1px dotted gray;
				margin: 0;
			}

		strong {
			display: inline-block;
			min-width: 200px;
		}

		span {
			padding-left: 10px;
		}
	</style>
</head>
<body>
	<div data-type="template" id="list-item">
		<strong>-{name}-</strong><span>-{age}-</span>
	</div>
	<script>
		function dynamicReplace(template, property, value) {
			var expr = '\\-\\{' + property + '\\}\\-';
			var re = new RegExp(expr, 'g');
			return template.replace(re, value);
		}

		function generateList(people, template) {
			var res = new Array("<ul>");
			for (var i = 0; i < people.length; i++) {
				var row = new String("<li>" + template + "</li>");
				for (j in people[i]) {
					row = dynamicReplace(row, j, people[i][j]);
				}
				res.push(row);
			}
			res.push("</ul>");

			return res.join('');
		}

		// JSON with people
		var people = [
						{ name: "Peter-The-Second", age: 14 },
						{ name: "Pesho", age: 23 },
						{ name: "Ivan", age: 20 },
						{ name: "Maya", age: 21 },
						{ name: "Monyo", age: 33 },
		];

		// Replace template with values
		var div = document.getElementById("list-item");
		if (div) {
			var template = div.innerHTML;
			var peopleList = generateList(people, template);
			if (peopleList) {
				div.innerHTML = peopleList;
				console.log(peopleList);
			}
		}
	</script>
</body>
</html>
